package com.lytxmd.boxtest.ui.bindwifi;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.hiflying.smartlink.ISmartLinker;
import com.hiflying.smartlink.OnSmartLinkListener;
import com.hiflying.smartlink.SmartLinkedModule;
import com.hiflying.smartlink.v7.MulticastSmartLinker;
import com.lytxmd.boxtest.R;
import com.lytxmd.boxtest.base.BaseActivity;
import com.lytxmd.boxtest.ui.debug.DebugBoxActivity;
import com.lytxmd.boxtest.utils.NetUtils;
import com.lytxmd.boxtest.utils.RouterUtils;
import com.lytxmd.boxtest.utils.ToastUtils;

import butterknife.BindView;


public class BindWifiActivity extends BaseActivity implements OnSmartLinkListener {
    public static final String EXTRA_SMARTLINK_VERSION = "EXTRA_SMARTLINK_VERSION";

    @BindView(R.id.editText_hiflying_smartlinker_ssid)
    EditText mSsidEditText;
    @BindView(R.id.editText_hiflying_smartlinker_password)
    EditText mPasswordEditText;
    @BindView(R.id.button_hiflying_smartlinker_start)
    Button mStartButton;

    protected ISmartLinker mSnifferSmartLinker;

    private boolean mIsConncting = false;
    protected Handler mViewHandler = new Handler();
    protected ProgressDialog mWaitingDialog;
    private BroadcastReceiver mWifiChangedReceiver;


    @Override
    protected void initParams(Bundle params) {

        mSnifferSmartLinker = MulticastSmartLinker.getInstance();

    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        initToolBar("配置盒子网络");
        mSsidEditText.setText(getSSid());


        mWaitingDialog = new ProgressDialog(this);
        mWaitingDialog.setCanceledOnTouchOutside(false);//触摸屏幕以外对话框不消失
        mWaitingDialog.setMessage(getString(R.string.hiflying_smartlinker_waiting));
        mWaitingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(R.string.hiflying_smartlinker_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        mWaitingDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //Toast.makeText(CustomizedActivity.this, "配置已取消", Toast.LENGTH_SHORT).show();
                mSnifferSmartLinker.setOnSmartLinkListener(null);
                mSnifferSmartLinker.stop();
                mIsConncting = false;
            }
        });

        mStartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = mPasswordEditText.getText().toString();
                if (TextUtils.isEmpty(password)) {
                    mPasswordEditText.setFocusable(true);
                    ToastUtils.show(BindWifiActivity.this, R.string.input_wifi_password);
                    return;
                }
                // TODO Auto-generated method stub
                if (!NetUtils.isWifi(BindWifiActivity.this)) {//判断手机是否连接WiFi
                    mSsidEditText.setText(getSSid());
                    ToastUtils.show(BindWifiActivity.this, R.string.error_check_net_connect);
                } else {
                    if (!mIsConncting) {
                        //设置要配置的ssid 和pswd
                        try {

                            mSnifferSmartLinker.setOnSmartLinkListener(BindWifiActivity.this);
                            //开始 smartLink
                            mSnifferSmartLinker.start(getApplicationContext(), mPasswordEditText.getText().toString().trim(),
                                    mSsidEditText.getText().toString().trim());
                            mIsConncting = true;
                            mWaitingDialog.show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        mWifiChangedReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (networkInfo != null && networkInfo.isConnected()) {
                    mSsidEditText.setText(getSSid());
                    mPasswordEditText.requestFocus();
                    mStartButton.setEnabled(true);
                } else {
                    mSsidEditText.setText(R.string.hiflying_smartlinker_no_wifi_connectivity);
                    mSsidEditText.requestFocus();
                    mStartButton.setEnabled(false);
                    if (mWaitingDialog.isShowing()) {
                        mWaitingDialog.dismiss();
                    }
                }
            }
        };
        registerReceiver(mWifiChangedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_customized;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSnifferSmartLinker.setOnSmartLinkListener(null);
        try {
            unregisterReceiver(mWifiChangedReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onLinked(final SmartLinkedModule module) {
        Log.w(TAG, "onLinked");
        mViewHandler.post(new Runnable() {
            @Override
            public void run() {
                ToastUtils.show(BindWifiActivity.this, R.string.hiflying_smartlinker_new_module_found);
            }
        });
    }


    @Override
    public void onCompleted() {
        Log.w(TAG, "onCompleted");
        mViewHandler.post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                mWaitingDialog.dismiss();
                ToastUtils.show(BindWifiActivity.this, R.string.hiflying_smartlinker_completed);
                mIsConncting = false;
                RouterUtils.gotoNext(BindWifiActivity.this,DebugBoxActivity.class);
                finish();
            }
        });
    }

    @Override
    public void onTimeOut() {
        Log.w(TAG, "onTimeOut");
        mViewHandler.post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                mWaitingDialog.dismiss();
                ToastUtils.show(BindWifiActivity.this, R.string.hiflying_smartlinker_timeout);
                mIsConncting = false;
            }
        });
    }


    //返回ssid名字
    private String getSSid() {

        WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo wi = wm.getConnectionInfo();
            if (wi != null) {
                String ssid = wi.getSSID();
                if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                    return ssid.substring(1, ssid.length() - 1);
                } else {
                    return ssid;
                }
            }
        }
        return "";
    }
}
